require 'time'

class Movie
  include Comparable
#  include Enumerable
  attr_reader :name
  attr_reader :showtime
  def initialize(name,showtime)
    @name = name
    if showtime.kind_of? Time
      @showtime = showtime      
    elsif showtime.kind_of? String
      @showtime = Time.parse(showtime)
    else
      raise ArgumentError, "Unable to parse #{showtime}" 
    end
    
  end

  def name_and_showtime
    showtime=@showtime.strftime("%I:%M %p")
    if @showtime > Time.now
      text="next show"
    else
      text="already started"
    end
    "#{@name}: #{text} at #{showtime}"
  end
  
  def <=>(movie)
    @showtime<=>movie.showtime
  end
  
end

module Enumerable
  # def group_by
  #   myhash=Hash.new
  #   self.each do |item|
  #     val=yield(item)
  #     if myhash[val].nil?
  #       myhash[val]=[item]
  #     else
  #       myhash[val] << item
  #     end
  #   end
  #   myhash
  # end
  
  def group_by
    self.inject({}) do |myhash, item|
      val=yield(item)
      if myhash[val].nil?
        myhash[val]=[item] 
      else
        myhash[val] << item
      end
      myhash
    end
  end
  
  
  
  def each_grouped_by_first_letter
    self.group_by { |x| x[0,1].to_s }.each do |key, value|
      yield(key,value)
    end
  end
end

class Range
  def each_even
    self.each do |number|
      yield(number) if number.modulo(2)==0
    end
  end
end


class IndifferentHash < Hash
  
  def []=(key,value)
    if key.kind_of?(String)
      key=key.to_sym
    end
    super(key,value)
  end
  
  def [](key)
    if key.kind_of?(String)
      key=key.to_sym
    end
    super(key)
  end
end

$movies = []
$movies << Movie.new("Orphan", Time.parse("1:00 pm"))
$movies << Movie.new("Orphan", Time.parse("4:05 pm"))
$movies << Movie.new("Orphan", Time.parse("7:00 pm"))
$movies << Movie.new("GI Joe", Time.parse("1:05 pm"))
$movies << Movie.new("GI Joe", Time.parse("4:30 pm"))
$movies << Movie.new("GI Joe", Time.parse("6:50 pm"))
$movies << Movie.new("Rocky Horror", Time.parse("12:00 am"))
$movies << Movie.new("District 9", Time.parse("11:00 am"))
$movies << Movie.new("District 9", Time.parse("3:00 pm"))

